package com.xiaoyun.service.impl;

import com.xiaoyun.bo.MerchantOrderBO;
import com.xiaoyun.enums.PaymentStatus;
import com.xiaoyun.enums.YesOrNo;
import com.xiaoyun.mapper.OrderStatusMapper;
import com.xiaoyun.mapper.OrdersMapper;
import com.xiaoyun.pojo.Orders;
import com.xiaoyun.pojo.PayOrders;
import com.xiaoyun.repository.PayOrdersRepository;
import com.xiaoyun.service.PaymentOrderService;
import lombok.RequiredArgsConstructor;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;

@Service
@RequiredArgsConstructor
public class PaymentOrderServiceImpl implements PaymentOrderService {


    private final Sid sid;

    private final PayOrdersRepository payOrdersRepository;


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public String updateOrderPaid(String merchantOrderId, Integer paidAmount) {
        PayOrders paidOrder = payOrdersRepository.findByMerchantOrderId(merchantOrderId);
        paidOrder.setPayStatus(PaymentStatus.PAID.type);
        paidOrder.setAmount(paidAmount);
        PayOrders payOrders = payOrdersRepository.save(paidOrder);

        return  payOrders.getReturnUrl();
    }

    @Override
    public PayOrders queryOrderByStatus(String merchantOrderId, String merchantUserId, Integer orderStatus) {
        return payOrdersRepository.findByMerchantUserIdAndMerchantOrderIdAndPayStatus(merchantOrderId, merchantUserId, orderStatus);
    }



    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean createPaymentOrder(MerchantOrderBO merchantOrderBO) {
        String id = sid.nextShort();
        PayOrders paymentOrder = new PayOrders();
        BeanUtils.copyProperties(merchantOrderBO, paymentOrder);
        paymentOrder.setId(id);
        paymentOrder.setComeFrom("天天吃货");
        paymentOrder.setIsDelete(YesOrNo.NO.type);
        paymentOrder.setCreatedTime(new Date());

        PayOrders save = payOrdersRepository.save(paymentOrder);

        return save != null ? true : false;
    }

    @Override
    public PayOrders queryOrderInfo(String merchantUserId, String merchantOrderId) {
        return payOrdersRepository.findByMerchantOrderIdAndMerchantUserId(merchantUserId, merchantOrderId);
    }
}
